package com.zondy.dizhi.server.util;

import java.io.File;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.DialogInterface.OnClickListener;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.net.Uri;
import android.os.Handler;
import android.os.Message;

import com.zondy.mapgis.android.environment.Environment;
import com.zondy.mapgis.android.environment.Environment.UpdateCallback;
import com.zondy.mapgis.android.utils.ToolToast;

public class ServerUtil
{

	// 应用下载地址
	private static String DOWNLOAD_APK_PATH = "";

	/**
	 * 检查是否有新版本
	 * 
	 * @param url 服务器url
	 * @param params 参数
	 * @param strVersion 产品当前版本
	 * @return true:有新版本，false:无新版本
	 */
	public static boolean IsUpdateVersion(String url, String params, String strVersion)
	{
		boolean bres = false;
		byte[] bytes = GsonUtil
				.getHtttpUrlBytes("http://www.smaryun.com/gis_formal_api.php?act=get_version_info&serial_no=1203aab7-74bb-4f4b-b16a-26481dfc4fd1");

		String read = GsonUtil.getBytesToString(bytes, "gb2312");

		while (read != null)
		{
			int ierr = read.indexOf("<version>");
			if (ierr != -1)
			{
				String strUpateVersion = read.substring(ierr + "<version>".length(), read.indexOf("</version>"));
				if (strUpateVersion.compareToIgnoreCase(strVersion) != 0)
				{
					bres = true;
				}
			}
		}

		return bres;
	}

	/**
	 * 检测产品更新并进行下载安装
	 */
	public static void UpdateVersion(final Activity ctx)
	{

		if (APPNetWork.isNetWork(ctx))
		{
			PackageManager packageManager = ctx.getPackageManager();
			try
			{

				PackageInfo packInfo = packageManager.getPackageInfo(ctx.getPackageName(), 0);
				final String version = packInfo.versionName;
				final String strParmas = "act= get_version_info&serial_no=" + "1203aab7-74bb-4f4b-b16a-26481dfc4fd1";
				new Thread(new Runnable()
				{
					@Override
					public void run()
					{
						boolean bUpdate = IsUpdateVersion("http://www.smaryun.com/gis_formal_api.php", strParmas, version);
					}
				}).start();
				// boolean bUpdate = Environment.IsUpdateVersion(ctx, version);
				if (true)
				{
					AlertDialog.Builder builder = new AlertDialog.Builder(ctx);
					builder.setTitle("版本更新提示");
					builder.setMessage("是否进行更新?");
					builder.setPositiveButton("是", new OnClickListener()
					{
						@Override
						public void onClick(DialogInterface dialog, int which)
						{
							ToolToast.showShort("你已经点击更新");
							// String strDownLoadUrl = strUpdateUrl +
							// "?act=download_addon&weight_id=" + strSerno;
							// http://www.smaryun.com/gis_formal_api.php?act=download_addon&weight_id=1203aab7-74bb-4f4b-b16a-26481dfc4fd1
							// String url = Environment.getUpdateAppUrl(ctx);
							// ctx.startService(DownloadService.createIntent(ctx,
							// url));
							ctx.startService(DownloadService.createIntent(ctx, "http://192.168.83.222:8888/Hello/MapGISExplorer.apk"));
						}
					});
					builder.setNegativeButton("否", new OnClickListener()
					{
						@Override
						public void onClick(DialogInterface dialog, int which)
						{
						}

					});
					builder.create().show();
				}
			}
			catch (NameNotFoundException e)
			{
				e.printStackTrace();
			}
		}
	}

	/**
	 * 检测产品更新并进行下载安装
	 */
	private static ProgressDialog progressDialog;
	private static boolean bUpdate = false;
	private static Context ctx;

	public ServerUtil(Context context)
	{
		this.ctx = context;
	}

	public static void UpdateVersion1(final Context ctx)
	{
		PackageManager packageManager = ctx.getPackageManager();
		try
		{
			PackageInfo packInfo = packageManager.getPackageInfo(ctx.getPackageName(), 0);
			String version = packInfo.versionName;
			DOWNLOAD_APK_PATH = android.os.Environment.getExternalStorageDirectory().getPath() + File.separator + packInfo.packageName + ".apk";

			Environment.isVersionUpdate(ctx, new UpdateCallback()
			{
				@Override
				public void onComplete(final boolean sucess)
				{
					((Activity) ctx).runOnUiThread(new Runnable()
					{
						@Override
						public void run()
						{
							if (sucess)
							{
								AlertDialog.Builder builder = new AlertDialog.Builder(ctx);
								builder.setTitle("版本更新提示");
								builder.setMessage("是否进行更新?");
								builder.setPositiveButton("是", new OnClickListener()
								{

									@Override
									public void onClick(DialogInterface dialog, int which)
									{
										progressDialog = new ProgressDialog(ctx);
										progressDialog.setTitle("下载中");
										progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
										progressDialog.setMessage("正在下载，请耐心等待...");
										progressDialog.setIndeterminate(false);
										progressDialog.setMax(100);
										progressDialog.setProgress(0);
										progressDialog.setCanceledOnTouchOutside(false);
										progressDialog.setCancelable(false); // 不响应返回键
										progressDialog.show();
										// final String url =
										// Environment.getUpdateAppUrl(ctx);
										final String url = null;

										new Thread()
										{
											@Override
											public void run()
											{
												DownLoadVersion(ctx, url);
											}
										}.start();
									}
								});
								builder.setNegativeButton("否", new OnClickListener()
								{

									@Override
									public void onClick(DialogInterface dialog, int which)
									{
									}

								});
								builder.create().show();

							}
						}
					});
				}
			});
		}
		catch (NameNotFoundException e)
		{
			e.printStackTrace();
		}
	}

	/**
	 * 下载
	 */
	private static void DownLoadVersion(Context ctx, String url)
	{
		url = "http://192.168.83.222:8888/Hello/MapGISExplorer.apk";
		LoadApkService loadApk = new LoadApkService(ctx, url, DOWNLOAD_APK_PATH, Downloadhandler);
		loadApk.call();

	}

	private static Handler Downloadhandler = new Handler()
	{
		@Override
		public void handleMessage(Message msg)
		{
			switch (msg.what)
			{
			case 1:
				if (msg.arg1 < 100)
				{
					progressDialog.setProgress(msg.arg1);
				}
				else if (msg.arg1 == 100)
				{
					if (progressDialog != null)
					{
						progressDialog.cancel();
						progressDialog.dismiss();
					}
					installApk((Activity) ctx, DOWNLOAD_APK_PATH);
					// installAppFile((Activity) ctx, DOWNLOAD_APK_PATH);
				}
				break;

			default:
				break;
			}
		}
	};

	/**
	 * ��װapk
	 * 
	 * @param url
	 */
	public static void installApk(Context context, String apkPath)
	{
		File apkfile = new File(apkPath);
		if (!apkfile.exists())
		{
			return;
		}
		Intent i = new Intent(Intent.ACTION_VIEW);
		i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		i.setDataAndType(Uri.parse("file://" + apkfile.toString()), "application/vnd.android.package-archive");
		context.startActivity(i);
		// 关闭旧版本的应用程序的进程
		// android.os.Process.killProcess(android.os.Process.myPid());

		// //apk文件的本地路径
		// File apkfile = new File(apkFilePath);
		// //会根据用户的数据类型打开android系统相应的Activity。
		// Intent intent = new Intent(Intent.ACTION_VIEW);
		// //设置intent的数据类型是应用程序application
		// intent.setDataAndType(Uri.parse("file://" + apkfile.toString()),
		// "application/vnd.android.package-archive");
		// //为这个新apk开启一个新的activity栈
		// intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		// //开始安装
		// startActivity(intent);
		// //关闭旧版本的应用程序的进程
		// android.os.Process.killProcess(android.os.Process.myPid());

	}

	/**
	 * 应用安装
	 * 
	 * @param activity 应用
	 * @param fileName 安装包位置
	 */
	private static void installAppFile(Activity activity, String filePath)
	{
		File file = new File(filePath);
		if (!file.exists())
			return;
		// file.delete();

		// try
		// {
		// file.createNewFile();
		// }
		// catch (IOException e1)
		// {
		// e1.printStackTrace();
		// }

		String cmd = "chmod 4755 " + filePath;
		try
		{
			Runtime.getRuntime().exec(cmd);
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}

		Uri data = null;
		data = Uri.fromFile(file);
		String type = "application/vnd.android.package-archive";
		Intent intent = new Intent(Intent.ACTION_VIEW);
		intent.setDataAndType(data, type);
		activity.startActivity(intent);
	}
}
